from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.urls import reverse
from myadmin.views import OpenStackToken

# Create your views here.

import requests,json,time
import myadmin.views.OpenStackToken

def index(request):
    # 通过render方法让html模板喧染页面
    url = OpenStackToken.flavorurl
    headers = OpenStackToken.getToken()
    flavorlist = json.loads(requests.get(url, headers=headers).text)
    datadict=[]

    for flavor in flavorlist['flavors']:
        flavorid = flavor['id']
        #根据id获取每一个flavor的详细值
        url_detail = url+"/"+flavorid
        flavordetail = json.loads(requests.get(url_detail, headers=headers).text)['flavor']
        #print(flavordetail)
        temp = {"id":flavorid,"name":flavor['name'],"ram":flavordetail['ram'],"vcpus":flavordetail['vcpus'],"disk":flavordetail['disk'],"swap":flavordetail['swap']}
        datadict.append(temp)

    #print(datadict)
    context = {"flavorlist": datadict}
    return render(request,"myadmin/flavor/index.html",context)

def add(request):
    '''加载添加信息'''
    return render(request, "myadmin/flavor/flavoradd.html")

def insert(request):
    '''执行信息添加'''
    try:
        flavorname = request.POST['flavorname']
        vcpus = request.POST['vcpus']
        ram = request.POST['ram']
        disk = request.POST['disk']
        swap = request.POST['swap']
        # 生成http提交时的body数据
        body = {
            "flavor": {
                "name": flavorname,
                "ram": ram,
                "vcpus": vcpus,
                "disk": disk,
                "swap": swap
            }
        }
        url = OpenStackToken.flavorurl
        headers = OpenStackToken.getToken()
        status_code = requests.post(url, data=json.dumps(body), headers=headers).text
        print(status_code)
        context = {"info": "添加成功！！"}
        return redirect(reverse("myadmin_flavor_index"))
    except Exception as err:
        return HttpResponse("出错啦："+str(err))


def delete(request,id=""):
    url_delete = OpenStackToken.flavorurl + "/" + id
    print(url_delete)
    headers = OpenStackToken.getToken()
    try:
        response = requests.delete(url_delete, headers=headers)
        return redirect(reverse("myadmin_flavor_index"))
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))

def edit(request,id=0):
    try:
        # 通过render方法让html模板喧染页面
        url = OpenStackToken.flavorurl+ "/" + str(id)
        headers = OpenStackToken.getToken()

        # 在2.55版本中新增description属性，如果要使用此属性这里要求指定版本
        headers['X-OpenStack-Nova-API-Version'] = "2.55"
        headers['Content-Type'] = "application/json"

        flavor = json.loads(requests.get(url, headers=headers).text)['flavor']

        if flavor:
            context = {"flavor": flavor}
            print(context)
            return render(request, "myadmin/flavor/flavoredit.html", context)
        else:
            return HttpResponse("未找到该实例类型信息！！")
    except Exception as err:
        return HttpResponse("是出错啦：" + str(err))


def update(request):
     '''执行编辑信息'''
     description = request.POST['description']
     flavorid = request.POST['flavorid']

    # 只能更改描述信息，其它信息不允许
     body = {
           "flavor": {
               "description": description,
          }
      }
     try:
         url = OpenStackToken.flavorurl + "/" + str(flavorid)
         headers = OpenStackToken.getToken()
         headers['X-OpenStack-Nova-API-Version'] = "2.55"
         headers['Content-Type'] = "application/json"
         status_code = requests.put(url,data=json.dumps(body), headers=headers).text
         print(status_code)
         return redirect(reverse("myadmin_flavor_index"))
     except Exception as err:
         return HttpResponse("是出错啦：" + str(err))
